import Vue               from 'vue'
import Router            from 'vue-router'
import store             from './store/store.js'
import config            from '@/common/router'
import api               from '@/api/api.js'
import defaultDictionary from '@/common/dictionary'
import {
	getUrlSearch,
	getUserInfo,
	getOrgInfo,
	getMenuData,
}                        from '@/utils/index.js'

Vue.use(Router)

const router = new Router(config)

router.beforeEach(async (to, from, next) => {
	if (!store.state.token || !store.state.sessionUser || !store.state.sessionOrg) {
		const token = getUrlSearch('token');
		
		//请求头要加的信息
		const userInfo = await getUserInfo({token});//用户信息
		const orgInfo  = await getOrgInfo({token});//org
		const menuData = await getMenuData({token});//菜单数据
		const dutyList = await api.get['/rest/rptTemplate/queryCode_dutyList']();//部门
		
		defaultDictionary.orgList = dutyList.data//设置部门
		
		
		store.commit('setState', {
			token,//请求头必须要带的
			sessionUser      : userInfo.id,//请求头必须要带的
			sessionOrg       : orgInfo,//请求头必须要带的
			userInfo,
			menuData,
			dictionaryMapping: defaultDictionary
		});
		
		// console.log('store.state.dictionaryMapping.orgList', store.state.dictionaryMapping.orgList);
	}
	
	next();
})
router.afterEach((to) => {
	//
	store.commit('setState', {
		defaultActive: to.path,
		belongTo     : to.meta.belongTo
	})
	//
	if (to.meta.title) {
		document.title = to.meta.title
	}
})

export default router
